package com.solace.selenium.config;

import com.solace.selenium.entity.Authorization;
import com.solace.selenium.service.AuthorizationService;
import com.solace.selenium.service.LogTimeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.AsyncHandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Component
@Slf4j
public class SecurityInterceptor implements AsyncHandlerInterceptor {
    @Autowired
    private AuthorizationService authorizationService;
    @Autowired
    private LogTimeService logTimeService;

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //log.info("postHandle");
        logTimeService.addLogOpsTime();
        logTimeService.removeMaxTime(1000);
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //log.info("preHandle");
        Authorization webInterceptor = authorizationService.getWebInterceptor();
        if (webInterceptor==null){
            throw new ServiceException("请激活机器码");
        }
        Long currentTime = System.currentTimeMillis();
        Long createKeyTime = webInterceptor.getCreateKeyTime();
        Long startTime = webInterceptor.getActivationTime();
        Long stopTime = webInterceptor.getStopKeyTime();
        if (startTime>currentTime){
            throw new ServiceException("本地时间异常START");
        }
        if (createKeyTime>currentTime){
            throw new ServiceException("本地时间异常CREATE");
        }
        Long max = logTimeService.getMax(currentTime);
        if (max>currentTime){
            throw new ServiceException("本地时间异常MAX");
        }
        if (currentTime>stopTime){
            throw new ServiceException("授权码已过期");
        }
        return true;
    }
}